"use strict";

/**
 * Created by xuchao on 15/10/16.
 */
angular.module('app.controller')
  .controller('HomeCtrl', function ($scope, RestService, $stateParams, $state, items, Toast) {

    $scope.array = items;

    $scope.rank = function () {
      $state.go('rank', {activityId: $stateParams.activityId});
    };


    $scope.injectArray = function () {
      angular.forEach($scope.array, function (item) {
        item.imgList = angular.fromJson(item.material);
        item.check = function () {
          $state.go('detail', {openid: $stateParams.openid, id:item.id, activityId: $stateParams.activityId});
        };
        item.vote = function () {
          if ($stateParams.openid) {
            $scope.loading = true;
            RestService.vote($stateParams.activityId, $stateParams.openid, item.id).$promise.then(function (data) {
              if (data.errCode == 1) {
                Toast.success('投票成功');
                var len = $scope.array.length;
                for (var i = 0; i < len; i++) {
                  var obj = $scope.array[i];
                  if (obj.id == $scope.detail.id) {
                    $scope.array[i].votes++;
                    break;
                  }
                }
              } else {
                Toast.fail(data.errMsg);
              }
            }).finally(function () {
              $scope.loading = false;
            });
          }else{
            $scope.noId = true;
          }
        };
      });
    };


    $scope.injectArray();


    (function () {
      var timeline = {
        title: '德州移动精英店长评选活动',
        link: 'http://activity.weixin.cloudatum.com/activity/dzmanager/index.html#/?activityId=' + $stateParams.activityId,
        imgUrl: 'http://activity.weixin.cloudatum.com/activity/dzmanager/assets/images/logo.jpg'
      };
      var message = {
        title: '德州移动精英店长评选活动',
        desc: '德州移动精英店长火爆评选中,内藏帅哥美女快来瞅瞅你认识几个',
        link: 'http://activity.weixin.cloudatum.com/activity/dzmanager/index.html#/?activityId=' + $stateParams.activityId,
        imgUrl: 'http://activity.weixin.cloudatum.com/activity/dzmanager/assets/images/logo.jpg'
      };
      wx.onMenuShareTimeline(timeline);
      wx.onMenuShareAppMessage(message);
    })();

  });
